/*
 * Copyright (c) 2010-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.wordpress;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import javax.swing.Box;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel;

import org.panteleyev.blogapi.Blog;
import org.panteleyev.blogapi.WordPressAccount;
import org.panteleyev.blogapi.WordPressAuthor;
import org.panteleyev.blogclient.BloggerFrame;
import org.panteleyev.blogclient.Options;
import org.panteleyev.swing.SwingFactory;
import org.panteleyev.swing.TableUtil;
import org.panteleyev.utilities.Updatable;

public class WordPressAuthorsFrame extends BloggerFrame<WordPressUserProfile> implements Updatable {
    private WordPressAccount            account;
    private ArrayList<WordPressAuthor>  authors = new ArrayList<>();

    private AbstractTableModel          tableModel;
    private JTable                      table = new JTable();
    private JScrollPane                 scroller = new JScrollPane(table);
    private JComboBox<String>           blogsComboBox;

    private static final String[] tableHeaderNames = {
        "id",
        "login",
        "name"
    };

    public WordPressAuthorsFrame(WordPressUserProfile profile) {
        super(profile);
        setTitle(L10N.AUTHORS_FRAME_TITLE.s());

        account = profile.getAccount();

        initComponents();
        createMenuBar();

        update();
    }

    public WordPressAccount getAccount() {
        return account;
    }

    private void initComponents() {
        DefaultComboBoxModel<String> blogListModel = new DefaultComboBoxModel<String>() {
            private ArrayList<Blog> blogs = getAccount().getBlogs();

            @Override
            public int getSize() {
                return blogs.size();
            }

            @Override
            public String getElementAt(int index) {
                return blogs.get(index).getName();
            }
        };

        tableModel = new AbstractTableModel() {
            @Override
            public int getColumnCount() {
                return tableHeaderNames.length;
            }

            @Override
            public int getRowCount() {
                return authors.size();
            }

            @Override
            public Object getValueAt(int row, int col) {
                WordPressAuthor a = authors.get(row);

                switch (col) {
                    case 0:
                        return a.getId();
                    case 1:
                        return a.getLogin();
                    case 2:
                        return a.getDisplayName();
                    default:
                        return null;
                }
            }

            @Override
            public String getColumnName(int column) {
                return tableHeaderNames[column];
            }
        };
        table.setModel(tableModel);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setInheritsPopupMenu(true);

        scroller.setPreferredSize(new Dimension(50, 50));
        scroller.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent evt) {
                TableUtil.adjustTableColumnSizes(table, 2, scroller);
            }
        });

        getContentPane().setLayout(new BorderLayout());

        getContentPane().add(
            SwingFactory.createToolBarPanel(
                createProfileToolBar(false, true),
                Box.createHorizontalStrut(5),
                blogsComboBox = new JComboBox<>(blogListModel),
                Box.createHorizontalGlue(),
                SwingFactory.createToolBar(false, true, getUpdateAction()),
                Box.createHorizontalStrut(5),
                getBusyLabel(),
                Box.createHorizontalStrut(5)
            ), BorderLayout.NORTH
        );

        blogsComboBox.setSelectedIndex(0);
        SwingFactory.setWidthMaximumToPreferred(blogsComboBox);

        getContentPane().add(scroller, BorderLayout.CENTER);

        Options.getBounds(this);
    }

    private void createMenuBar() {
        createMenuBar(
            createFileMenu(),
            createProfileMenu(),
            createToolsMenu(),
            createWindowMenu(),
            createHelpMenu()
        );
    }

    private Blog getSelectedBlog() {
        int blogIndex = blogsComboBox.getSelectedIndex();
        return getAccount().getBlog(blogIndex);
    }

    @Override
    public void update() {
        getBusyLabel().setBusy(true);
        enableActions(false);

        new SwingWorker<ArrayList<WordPressAuthor>,Object>() {
            @Override
            protected ArrayList<WordPressAuthor> doInBackground() throws Exception {
                return getAccount().getAuthors(getSelectedBlog());
            }

            @Override
            protected void done() {
                try {
                    authors = get();
                } catch (InterruptedException | ExecutionException ex) {
                    handleException(ex);
                } finally {
                    tableModel.fireTableDataChanged();
                    TableUtil.adjustTableColumnSizes(table, 2, scroller);
                    getBusyLabel().setBusy(false);
                    enableActions(true);
                }
            }
        }.execute();
    }

    private void enableActions(boolean b) {
        getUpdateAction().setEnabled(b);
    }
}
